<?php
include '../../control.php';
class mygit extends git
{
    /**
     * Sync from the syncer by api. // FromGitlab
     * 
     * @access public
     * @return void
     */
    public function apiSync()
    {
        $data = json_decode(file_get_contents('php://input'));
        if (!$_SERVER['X-Gitlab-Token'] || ($_SERVER['X-Gitlab-Token'] != $this->config->git->gitlabToken)) {
            return;
        }
        if(!$data->commits) {
            return;
        }

        if ($data->object_kind != 'push') {
            return;
        }

        $repoRoot = ''; // todo $this->post->repoRoot;

        $parsedLogs = array();
        
        foreach($data->commits as $log)
        {
            $parsedLog = new stdClass();

            // 根据邮箱找账号
            $account = $log->author->email;
            $user = $this->dao->select('*')->from(TABLE_USER)->where("email")->eq($log->author->email)->fetch();
            if ($user) {
                $account = $user->account;
            }

            $parsedLog->author    = $account;
            $parsedLog->revision  = $log->id;
            $parsedLog->msg       = trim($log->message);
            $parsedLog->date      = date('Y-m-d H:i:s', strtotime($log->timestamp));

            $parsedLog->files     = [];
            if ($log->modified) {
                $parsedLog->files['M'] = $log->modified;
            }
            
            if ($log->removed) {
                $parsedLog->files['D'] = $log->removed;
            }
            $parsedLogs[] = $parsedLog;
        }

        $parsedObjects = array('stories' => array(), 'tasks' => array(), 'bugs' => array());
        foreach($parsedLogs as $log)
        {
            $objects = $this->git->parseComment($log->msg);
            if($objects)
            {
                $this->git->saveAction2PMS($objects, $log, $repoRoot);
                if($objects['stories']) $parsedObjects['stories'] = array_merge($parsedObjects['stories'], $objects['stories']);
                if($objects['tasks'])   $parsedObjects['tasks'  ] = array_merge($parsedObjects['tasks'],   $objects['tasks']);
                if($objects['bugs'])    $parsedObjects['bugs']    = array_merge($parsedObjects['bugs'],    $objects['bugs']);
            }
        }
        $parsedObjects['stories'] = array_unique($parsedObjects['stories']);
        $parsedObjects['tasks']   = array_unique($parsedObjects['tasks']);
        $parsedObjects['bugs']    = array_unique($parsedObjects['bugs']);

        $this->view->parsedObjects = $parsedObjects;
        $this->display();
        exit;
    
    }
}